//
//  YTOrderManagerViewController.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/6/2.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTOrderManagerViewController.h"
#import "YTPickedOrderViewCell.h"
#import "YTOrderFilterView.h"
#import "YTOrderManagerViewModel.h"
#import "YTOrderDetailViewController.h"
#import "YTPopupView.h"
#import "YTPickedOrderModel.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

@interface YTOrderManagerViewController ()<
UITableViewDelegate,
UITableViewDataSource,
DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate>
@property (strong, nonatomic) YTPopupView *popView;
@property (weak, nonatomic) IBOutlet UIView *segmentView;
@property (strong, nonatomic) YTOrderManagerViewModel *viewModel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation YTOrderManagerViewController

- (void)initialize {
    _viewModel = [[YTOrderManagerViewModel alloc] init];
    @weakify(self);
    [self.tableView addLoadDataControl:^{
        @strongify(self);
        [self.viewModel.loadMoreDataCommand execute:nil];
    }];
    
    [self.tableView addRefreshControl:^{
        @strongify(self);
        [self.viewModel.requestRemoteDataCommand execute:nil];
        [self.tableView.mj_header endRefreshing];
    }];
    
    [[[[NSNotificationCenter defaultCenter]
       rac_addObserverForName:YTPickOrderSuccessNofitication object:nil]
      subscribeOn:[RACScheduler mainThreadScheduler]]
     subscribeNext:^(NSNotification *notify) {
         @strongify(self);
         [self performSegueWithIdentifier:@"YTShowOrderDetail" sender:notify.object];
     }];
}

- (void)bindViewModel {
    [self userinterfaceControl];
    @weakify(self);
    YTSegmentedControlConfig *config = [[YTSegmentedControlConfig alloc] init];
    config.indecatorWidth = 70;
    config.titleSize = 15;
    
    YTSegmentedControl *segmentControl = [[YTSegmentedControl alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)
                                                                            titles:_viewModel.tabTitleArray
                                                                     configuration:config];
    segmentControl.didSelectedItem = ^(NSInteger index) {
        @strongify(self);
        [self.viewModel.changeTabCommand execute:@(index)];
    };
    [self.segmentView addSubview:segmentControl];
    
    [_viewModel.requestRemoteDataCommand execute:nil];
}

#pragma mark - UI控制

- (void)userinterfaceControl {
    @weakify(self);
    [_viewModel.requestRemoteDataCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    [_viewModel.changeTabCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    [_viewModel.filterCommand.executing subscribeNext:[self yt_showHudWithTips:nil]];
    
    // 刷新
    void (^refresh)(id x) = ^(id x) {
        @strongify(self);
        [self.tableView setContentOffset:CGPointMake(0, 0)];
        [self.tableView reloadData];
    };
    
    [[_viewModel.requestRemoteDataCommand.executionSignals switchToLatest] subscribeNext:refresh];
    [[_viewModel.changeTabCommand.executionSignals switchToLatest] subscribeNext:refresh];
    [[_viewModel.filterCommand.executionSignals switchToLatest] subscribeNext:refresh];
    [[_viewModel.loadMoreDataCommand.executionSignals switchToLatest]
     subscribeNext:^(NSArray<YTPickedOrderModel *> *data) {
         @strongify(self);
         if (data.count < 20) {
             [self.tableView.mj_footer endRefreshingWithNoMoreData];
         } else {
             [self.tableView.mj_footer endRefreshing];
         }
         [self.tableView reloadData];
     }];
}

#pragma mark - UITableViewDeleagte

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YTPickedOrderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTOrderManager" forIndexPath:indexPath];
    cell.model = _viewModel.pickedDataArray[indexPath.row];
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _viewModel.pickedDataArray.count;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _viewModel.pickedDataArray.count - 10 && _viewModel.pickedDataArray.count >= 20) {
        [tableView.mj_footer beginRefreshing];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self performSegueWithIdentifier:@"YTShowOrderDetail" sender:_viewModel.pickedDataArray[indexPath.row].orderId];
}

- (IBAction)filterAction:(UIBarButtonItem *)sender {
    [self.popView showWithLayout:YTPopupLayoutMake(YTPopupHorizontalLayoutLeft, YTPopupVerticalLayoutCenter)];
}

#pragma mark - DZNEmptyDataSetSource

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"当前暂无订单";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0f],
                                 NSForegroundColorAttributeName: kGrayColor};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"public_norecord"];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -100;
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"YTShowOrderDetail"]) {
        YTOrderDetailViewController *detail = segue.destinationViewController;
        detail.order_id = sender;
        detail.isPicked = YES;
    }
}

#pragma mark - lazy

- (YTPopupView *)popView {
    YTOrderFilterView *filter = [[YTOrderFilterView alloc] initWithFrame:CGRectMake(0, 0, 270, kScreenHeight)];
    filter.isShowPastOrder = YES;
    [filter loadCityData:_viewModel.serviceCitys];
    _popView  = [YTPopupView popupWithContentView:filter];
    _popView.showType = YTPopupShowTypeSlideInFromLeft;
    _popView.dismissType = YTPopupDismissTypeSlideOutToLeft;
    @weakify(self);
    filter.completeAction = ^(NSDictionary *dict){ //点击完成
        @strongify(self);
        [_popView dismiss:YES];
        [self.viewModel.filterCommand execute:dict];
    };
    
    filter.resetAction = ^{
        @strongify(self);
        [_popView dismiss:YES];
        [self.viewModel.requestRemoteDataCommand execute:nil];
    };
    
    return _popView;
}

@end
